<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { apiGet } from '@/request/apiUtils';
import moment from 'moment';
const formatDate = (d: any) => moment(d).format('YYYY-MM-DD');

const if_extension_list: TObj = {
    1: '是',
    0: '否',
}
const initQuery = {
    demand_id: undefined,
    task_id: undefined,
    task_type: undefined,
    assigned_to: undefined,
    task_name: undefined,
    left_time: undefined,
    estimate_time: undefined,
    version: undefined,
    task_data: undefined,
};
const { value: state } = ref({
    loading: false,
    tableData: [] as TObj[],
    total: 0,
    pageSize: 20,
    currentPage: 1,
    queryData: { ...initQuery },
    maxtime: "",
    mintime: "",
    gantter_status: false,
    table_span: 24,
    gantt_span: 12,
});


const myBarList = ref([] as TObj[])
const startTime = ref([] as TObj[])
const endTime = ref([] as TObj[])

const fetchData = async (page = state.currentPage, size = state.pageSize) => {
    state.loading = true;
    try {
        const apiUrl = '/tasks';
        const { task_data } = state.queryData;
        const params: TObj = {
            page,
            size,
            ...state.queryData,
            ...task_data
                ? {
                    task_start_data: formatDate(task_data[0]),
                    task_end_data: formatDate(task_data[1]),
                }
                : {},
        };
        console.log('params', params)
        delete params.task_data;
        const response: TObj = await apiGet(apiUrl, params); // 假设你有一个 API 端点返回数据
        state.tableData = response?.results || [];
        state.total = response?.count || 0;

        myBarList.value = []
        startTime.value = []
        endTime.value = []
        for (let i in state.tableData) {
            const bar = [{
                myBeginDate: state.tableData[i]['est_started'] + " 00:00",
                myEndDate: state.tableData[i]['deadline'] + " 00:00",
                ganttBarConfig: {
                    id: state.tableData[i]['demand_id'],
                    label: state.tableData[i]['task_name']
                }
            }]
            if (state.tableData[i]['est_started'] != null) {
                startTime.value.push(state.tableData[i]['est_started'])
            }
            if (state.tableData[i]['deadline'] != null) {
                endTime.value.push(state.tableData[i]['deadline'])
            }
            myBarList.value.push(bar)
        }
        console.log('myBarList', myBarList)
        if (endTime.value.length != 0 && startTime.value.length != 0) {
            state.maxtime = endTime.value.sort()[endTime.value.length - 1] + " 00:00";
            state.mintime = startTime.value.sort()[0] + " 00:00";
        } else {
            state.maxtime = moment().add(5, 'days').format('YYYY-MM-DD') + " 00:00";
            state.mintime = moment().format('YYYY-MM-DD') + " 00:00";
        }
        console.log('state.mintime', state.mintime)
        console.log('state.maxtime', state.maxtime)

    } catch (error) {
        console.error('Error fetching data:', error);
    }
    state.loading = false;
};

// 页数改变
const handleSizeChange = (val: number) => {
    state.pageSize = val;
    fetchData(state.currentPage, val);
};
const handleCurrentChange = (val: number) => {
    state.currentPage = val;
    fetchData(val, state.pageSize);
};

// 重置
const handleReset = () => {
    // console.log('initQuery', initQuery);
    state.queryData = { ...initQuery };
    // fetchData()
};
// 查询
const handleSearch = () => {
    fetchData()
};

const hanleChangeGatter = () => {
    state.gantter_status = !state.gantter_status
    if (state.gantter_status) {
        state.table_span = 8;
        state.gantt_span = 16;
    } else {
        state.table_span = 24;
        state.gantt_span = 0;
    }
};

onMounted(() => {
    fetchData();
});

</script>

<template class="home-wrap">
    <div class="home-search">
        <div class="home-search-inner">
            <el-input v-model="state.queryData.demand_id" placeholder="请输入需求ID" class="width200" />
            <el-input v-model="state.queryData.task_id" placeholder="请输入任务ID" class="width200" />
            <el-input v-model="state.queryData.task_type" placeholder="请输入任务类型" class="width200" />
            <el-input v-model="state.queryData.task_name" placeholder="请输入任务名称" class="width200" />
            <el-input v-model="state.queryData.assigned_to" placeholder="请输入指派人" class="width200" />
            <el-input-number v-model="state.queryData.estimate_time" placeholder="请输入预计工时" class="width200" />
            <el-input-number v-model="state.queryData.left_time" placeholder="请输入剩余工时" class="width200" />
            <el-input v-model="state.queryData.version" placeholder="请输入项目名称" class="width200" />
            <div class="date-wrap">
                <el-date-picker v-model="state.queryData.task_data" type="daterange" range-separator="-"
                    start-placeholder="任务开始日期" end-placeholder="任务结束日期" />
            </div>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button type="primary" @click="handleReset">重置</el-button>
            <el-button type="warning" @click="hanleChangeGatter">甘特图开关</el-button>
        </div>
    </div>

    <el-row>
        <el-col :span="state.table_span">
            <el-table :data="state.tableData" border style="width: 100%;" v-loading="state.loading"
                :header-cell-style="{ color: '#000', backgroundColor: '#61c5fc', height: '81px' }"
                :row-style="{ backgroundColor: '#cce4fa' }">
                <el-table-column prop="assigned_to" label="指派人" width="70" fixed="left" />
                <el-table-column prop="task_id" label="任务ID" width="70" fixed="left" />
                <el-table-column prop="task_name" label="任务名称" width="368" fixed="left" v-if="!state.gantter_status">
                    <template v-slot="scope">
                        <div class="ellipsis">{{ scope.row.task_name }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="task_type" label="任务类型" width="60" fixed="left"/>
                <el-table-column prop="status" label="任务状态" width="60" fixed="left" />
                <el-table-column prop="estimate_time" label="预计工时" width="60" />
                <el-table-column prop="left_time" label="剩余工时" width="60" />
                <el-table-column prop="demand_id" label="需求ID" width="70" />
                <el-table-column prop="demand_name" label="需求名称" width="400">
                    <template v-slot="scope">
                        <div class="ellipsis">{{ scope.row.demand_name }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="version" label="项目名称" width="200">
                    <template v-slot="scope">
                        <div class="ellipsis">{{ scope.row.version }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="est_started" label="开始日期" width="100" />
                <el-table-column prop="deadline" label="结束日期" width="100" />
                <el-table-column prop="if_extension" label="是否延期" width="88">
                    <template v-slot="scope">
                        <span :style="{ color: scope.row.if_extension === 1 ? 'red' : '' }">{{
                            if_extension_list[scope.row.if_extension] || '-' }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </el-col>

        <el-col :span="state.gantt_span" v-if="state.gantter_status">
            <g-gantt-chart :chart-start="state.mintime" :chart-end="state.maxtime" precision="day" row-height="40"
                width="100%" bar-start="myBeginDate" bar-end="myEndDate" grid="true" current-time="true">
                <g-gantt-row v-for="(bar, index) in myBarList" :key="index" :bars="bar"/>
            </g-gantt-chart>
        </el-col>

    </el-row>

    <div class="example-pagination-block">
        <span class="m-r-5 font-12">共 {{ state.total }}</span>
        <el-pagination v-model:currentPage="state.currentPage" v-model:page-size="state.pageSize"
            :page-sizes="[20, 50, 100, 200]" :small="true" :disabled="false" :background="false"
            layout="sizes, prev, pager, next" :total="state.total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </div>
</template>

<style scoped>
.home-wrap {
    position: relative;
}

.home-search {
    height: 80px;
}

.sta-wrap {
    display: flex;
    height: 20px;
    align-items: center;
    color: blue;
    font-size: 14px;
}

.home-search-inner {
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;
    gap: 10px;
}

.home-table {
    height: calc(100vh - 210px);
}

.example-pagination-block {
    display: flex;
    height: 40px;
    align-items: center;
    justify-content: end;
}
</style>
